#!usr/bin/env python  
# -*- coding:utf-8 _*-
""" 
@author:robot
@file: v1api02_dataflows.py 
@version:
@time: 2022/05/10 
"""
import json
import time

from TapClientCore.T02_tm_api.v1_api.v1_api_base import *


class V1DataFlows(V1ApiBase):

    def __init__(self, change=''):
        super(V1DataFlows, self).__init__(change)
        self.url_dataflows = api_joint(self.server, 'DataFlows')
        self.url_dataflows_findone = api_joint(self.url_dataflows, 'findOne')
        self.url_dataflows_draft = api_joint(self.url_dataflows, 'draft')
        self.url_dataflows_update = api_joint(self.url_dataflows, 'update')
        self.url_dataflows_remove_all = api_joint(self.url_dataflows, 'removeAll')
        self.url_dataflows_stages = api_joint(self.url_dataflows, 'stages')
        self.url_dataflows_metadata = api_joint(self.url_dataflows, 'metadata')

    # 创建
    def post_dataflows(self, payload):
        payload["rollback"] = "all"
        if self.setting.get('apiVersion') in ['v1.27']:
            from TapClientCore.T02_tm_api.v1_api.v1_api_module.v1api00_settings import V1Settings
            version_id = V1Settings().post_settings_object_id(self.access_token)
            _count = 0
            payload['id'] = version_id
            while True:
                try:
                    response = self.tapclient(
                        self.post,
                        self.url_dataflows,
                        json=payload
                    )
                    if response.get('code') == '110500':
                        logger.fatal(response)
                        raise Exception
                    else:
                        return response
                except Exception:
                    _count += 1
                    if _count == 5:
                        self.ERROR = True
                        return False
                    time.sleep(3)
                    continue
        else:
            while True:
                response = self.tapclient(
                    self.post,
                    self.url_dataflows,
                    json=payload
                )
                if response["msg"] == 'Error: Loading data source schema':
                    raise LoadSchemaError
                else:
                    return response

    # 删除 by where
    # {"_id":{"inq":["6290200d50f48400c9dc39d4"]}}
    def post_dataflows_removeall(self, where):
        w = json.dumps(where)
        response = self.tapclient(
            self.post,
            self.url_dataflows_remove_all
            + self.where(w)
        )
        return response

    # 查询 by filter
    """
    {"order":"createTime DESC",
    "limit":20,
    "fields":{"id":true,"name":true,"status":true,"executeMode":true,"category":true,"stopOnError":true,"last_updated":true,"createTime":true,"children":true,"stats":true,"checked":true,"stages":true,"setting":true,"user_id":true,"startTime":true,"listtags":true,"mappingTemplate":true,"platformInfo":true,"agentId":true},
    "skip":0,
    "where":{"mappingTemplate":"cluster-clone"}}
    """

    def get_dataflows_by_filter(self, _filter):
        f = json.dumps(_filter)
        response = self.tapclient(
            self.get,
            self.url_dataflows
            + self.filter(f)
        )
        return response

    # patch dataflow
    def patch_dataflows(self, payload):
        response = self.tapclient(
            self.patch,
            self.url_dataflows_draft,
            json=payload
        )
        return response

    # 修改 dataflow {"_id":{"in":["62901fcb50f48400c9dc3932"]}}
    def post_dataflows_update(self, where, payload):
        w = json.dumps(where)
        response = self.tapclient(
            self.post,
            self.url_dataflows_update
            + self.where(w),
            json=payload
        )
        return response

    # 查询 详细信息 by id
    def get_dataflows_by_id(self, dataflows_id):
        response = self.tapclient(
            self.get,
            api_joint(
                self.url_dataflows,
                dataflows_id
            )
        )
        return response

    # --- old ----

    # 查询
    def get_dataflows(self):
        response = self.tapclient(
            self.get,
            self.url_dataflows
        )
        return response

    # 查询findone
    def get_dataflows_findone(self):
        response = self.tapclient(
            self.get,
            self.url_dataflows_findone
        )
        return response

    # 查询findone by filter
    def get_dataflows_findone_by_filter(self, _filter):
        f = json.dumps(_filter)
        response = self.tapclient(
            self.get,
            self.url_dataflows_findone
            + self.filter(f)
        )
        return response

    # 重置任务
    def post_dataflows_reset_by_id(self, dataflows_id):
        if self.tapdata_product == 'dfs':
            response = self.tapclient(
                self.post,
                api_joint(
                    self.url_dataflows,
                    'resetAll'
                ),
                json={'id': [dataflows_id]}
            )
        else:
            response = self.tapclient(
                self.post,
                api_joint(
                    self.url_dataflows,
                    dataflows_id,
                    'reset'
                )
            )
        return response

    # 模型推演
    def post_dataflows_metadata(self, payload):
        payload["rollback"] = "all"
        if self.setting.get('apiVersion') in ['v1.27']:
            from TapClientCore.T02_tm_api.v1_api.v1_api_module.v1api00_settings import V1Settings
            version_id = V1Settings().post_settings_object_id(self.access_token)
            payload['id'] = version_id
            response = self.tapclient(
                self.post,
                self.url_dataflows_metadata,
                json=payload
            )
            time.sleep(3)
            response['id'] = version_id
        else:
            response = self.tapclient(
                self.post,
                self.url_dataflows_metadata,
                json=payload
            )
        return response
